package com.hyjx.framework.service;

import com.hyjx.framework.common.PropertyUtil;
import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.component.propertyconfig.PropertyConfigModel;
import com.hyjx.framework.component.propertyconfig.PropertyConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统配置 管理器
 *
 * @author peter
 */
public class ConfigManager {
    private static final Log logger = LogFactory.getLog(ConfigManager.class);
    
    /**
     * 初始化数据至缓存
     */
    public static void init() {
        PropertyConfigService configService = (PropertyConfigService) SpringBeanUtil.getBean("propertyConfigServiceImpl");
        List<PropertyConfigModel> list = configService.getAllConfigs();
        
        Map<String, String> configs = new LinkedHashMap<String, String>();
        for (PropertyConfigModel model : list) {
            configs.put(model.getProperty_key(), model.getProperty_value());
        }
        
        CacheService.set("sys.config.all", configs);
    }
    
    /**
     * 取所有配置信息--自缓存
     */
    public static Map<String, String> getAllConfig() {
        Object obj = CacheService.get("sys.config.all");
        if (obj == null) {
            return new LinkedHashMap<String, String>();
        } else {
            return (Map<String, String>) obj;
        }
    }
    
    /**
     * 取配置信息--自缓存
     */
    public static String getConfig(String configKey, String defaultValue) {
        String value = PropertyUtil.getValue(configKey);
        if (StringUtils.isBlank(value)){
            return defaultValue;
        }
        return value;
    }
    /**
     * 取配置信息--自缓存
     */
    public static String getConfig(String configKey) {
        String result = PropertyUtil.getValue(configKey);
        if (result != null && !"".equals(result)) {
            return result;
        }
        
        Object obj = CacheService.get("sys.config.all");
        Map<String, String> map;
        if (obj == null) {
            return "";
        } else {
            map = (Map<String, String>) obj;
            if (map.containsKey(configKey)) {
                return map.get(configKey);
            } else {
                return "";
            }
        }
    }
    
    /**
     * 取页面布局方式
     */
    public static String getUiLayout() {
        return getConfig("ui.layout");
    }
    
    /**
     * 取附件存储根路径
     *
     * @return
     */
    public static String getAttatchmentsPath() {
        return getConfig("attatchments.path");
    }
    
    /**
     * 取图片存储根路径
     */
    public static String getAttatchmentsPicPath() {
        return getConfig("attatchments.picPath");
    }
}